package com.zjgsu.coursecalendar.controller;

import com.zjgsu.coursecalendar.WebSecurityConfig;
import com.zjgsu.coursecalendar.model.User;
import com.zjgsu.coursecalendar.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY)String account, Model model){

        return "index";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/loginVerify")
    public String loginVerify(String username,String password,HttpSession session){
        User user1 = new User();
        user1.setUserAccount(username);
        user1.setUserPassword(password);
        int verify1 = userService.login(user1);
        if (verify1 == 1){
            session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
            return "admin";
        }else if (verify1 == 2){
            session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
            return "teacher";
        }else if (verify1 == 3){
            session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
            return "student";
        }else {
            return "redirect:/login";
        }
/*        Student user = new Student();
        user.setStudentAccount(username);
        user.setStudentPassword(password);
        boolean verify = loginService.verifyStudentLogin(user);
        if (verify) {
            session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
            return "index";
        } else {
            return "redirect:/login";
        }*/

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }
}
